package com.aspira.algorithm;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.SingleKeyTableShardingAlgorithm;
import com.google.common.collect.Range;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.LinkedHashSet;

public class ModuloTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Long> {
    private static final Logger log = LoggerFactory.getLogger(ModuloTableShardingAlgorithm.class);

    @Override
    public String doEqualSharding(Collection<String> tableNames, ShardingValue<Long> shardingValue) {
        log.info("collection:" + JSON.toJSONString(tableNames) + ",preciseShardingValue:" + JSON.toJSONString(shardingValue));
        for (String tableName: tableNames){
            if(tableName.endsWith(shardingValue.getValue() % 2 + "")){
                return tableName;
            }
        }
        throw new IllegalArgumentException();
    }

    @Override
    public Collection<String> doInSharding(Collection<String> tableNames, ShardingValue<Long> shardingValue) {
        log.info("collection:" + JSON.toJSONString(tableNames) + ",preciseShardingValue:" + JSON.toJSONString(shardingValue));
        Collection<String> result = new LinkedHashSet<>(tableNames.size());
       for (Long value : shardingValue.getValues()){
           for (String tableName: tableNames){
               if (tableName.endsWith(value % 2 + "")){
                   result.add(tableName);
               }
           }
       }


        return result;
    }

    @Override
    public Collection<String> doBetweenSharding(Collection<String> tableNames, ShardingValue<Long> shardingValue) {
        log.info("collection:" + JSON.toJSONString(tableNames) + ",preciseShardingValue:" + JSON.toJSONString(shardingValue));
        Collection<String> result = new LinkedHashSet<>(tableNames.size());
        Range<Long> valueRange = shardingValue.getValueRange();
        for (Long i = valueRange.lowerEndpoint(); i <= valueRange.upperEndpoint(); i++){
            for (String tableName: tableNames){
                if(tableName.endsWith(i %2 + "")){
                    result.add(tableName);
                }
            }
        }

        return result;
    }
}
